package com.joysuch.wwyt.datadump.biz.processor;

import cn.zlg.common.datadump.annotation.DataDumpEntity;
import cn.zlg.common.datadump.processor.BaseImportEntityProcessor;
import cn.zlg.common.util.CollectionUtils;
import com.google.common.collect.Lists;
import com.joysuch.wwyt.core.entity.BaseImageTypeRepository;
import com.joysuch.wwyt.core.repository.BaseImageTypeRepositoryDao;
import com.joysuch.wwyt.core.service.BizCodeGeneratorFacade;
import com.joysuch.wwyt.datadump.biz.model.MhMonitorPointDumpBean;
import com.joysuch.wwyt.mh.entity.MhMonitoringPoint;
import com.joysuch.wwyt.mh.entity.MhMonitoringType;
import com.joysuch.wwyt.mh.repository.MhMonitoringPointDao;
import com.joysuch.wwyt.mh.repository.MhMonitoringTypeDao;
import com.joysuch.wwyt.workflow.service.WorkFlowProcessService;
import com.mysema.commons.lang.Assert;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class MhMonitorPointProcessor extends BaseImportEntityProcessor<MhMonitorPointDumpBean, MhMonitoringPoint> {

    @Autowired
    private MhMonitoringPointDao pointDao;
    @Autowired
    private MhMonitoringTypeDao typeDao;
    @Autowired
    private BaseImageTypeRepositoryDao baseImageTypeRepositoryDao;
    @Autowired
    private WorkFlowProcessService workFlowProcessService;
    @Autowired
    private BizCodeGeneratorFacade bizCodeGeneratorFacade;

    /**
     * 保存后执行，确保新增、修改实体，entity都是持久化对象。
     * 如果是 processBeforeSave(), 创建的实体如果已经存在，将复制 DumpBean中importIgnore=false的属性，导致monitoringType属性丢失
     *
     * @param origin
     * @param entity
     * @param annotation
     * @return
     */
    @Override
    public MhMonitoringPoint processBeforePersist(MhMonitorPointDumpBean origin, MhMonitoringPoint entity, DataDumpEntity annotation, boolean override) {
        // 替换监测点类型与单位的中文括号 ()
        String[] typeAndUnit = parseNameAndUnit(origin.getMonitoringTypeName().replace("（", "(").replace("）", ")"));
        System.err.println(Arrays.toString(typeAndUnit));
        MhMonitoringType type = null;
        if (typeAndUnit.length == 1) {
            List<MhMonitoringType> types = typeDao.findByNameAndUnitIsNull(typeAndUnit[0]);
            Assert.isTrue(types.size() <= 1, String.format("监测类型[%s]存在多种，无法选择", typeAndUnit[0]));
            type = types.isEmpty() ? null : types.get(0);
        } else {
            List<MhMonitoringType> types = typeDao.findByNameAndUnit(typeAndUnit[0], typeAndUnit[1]);
            Assert.isTrue(types.size() <= 1, String.format("监测类型[%s(%s)]存在多种，无法选择", typeAndUnit[0], typeAndUnit[1]));
            type = types.isEmpty() ? null : types.get(0);
        }

        if (type == null) {
            type = createNewType(typeAndUnit, origin.getShowInMapIndependent());
            typeDao.save(type);
        } else {
            if (type.getCategoryId().equals(1) && type.getImageId() == null) {
                type = setDefaultPicture(type);
                typeDao.save(type);
            }
        }
        entity.setMhMonitoringType(type);
        entity.setUnit(type.getUnit());
        //保存大屏专栏配置
        if (type.getCategoryId() != null && type.getCategoryId().equals(1L)) {
            workFlowProcessService.saveConfigFromMhPointType(type);
        }
        return entity;
    }

    private MhMonitoringType createNewType(String[] typeAndUnit, String showInMapIndependent) {
        MhMonitoringType t = new MhMonitoringType();
        t.setName(typeAndUnit[0]);
        if (typeAndUnit.length > 1) {
            t.setUnit(typeAndUnit[1]);
        }
        if ("是".equals(showInMapIndependent)) {
            t.setCategoryId(1L);
            t = setDefaultPicture(t);
        } else {
            t.setCategoryId(0L);
        }
        if (t.getCode() == null) {
            t.setCode(bizCodeGeneratorFacade.jiancedianleixing());
        }
        return t;
    }

    //如果是环境监测点 默认设置第一个图标
    private MhMonitoringType setDefaultPicture(MhMonitoringType t) {
        List<BaseImageTypeRepository> types = baseImageTypeRepositoryDao.findByTypeCodes(Lists.newArrayList("environment_point"));
        if (!CollectionUtils.isEmpty(types)) {
            t.setImageId(types.get(0).getImageId());
        }
        return t;
    }

    private String[] parseNameAndUnit(String monitoringTypeName) {
        Pattern p = Pattern.compile("([^()]+)(\\(([^()]+)\\))?");
        Matcher m = p.matcher(monitoringTypeName);
        if (m.find()) {
            String name = m.group(1);
            if (m.group(3) != null) {
                return new String[]{m.group(1), m.group(3)};
            }
            return new String[]{m.group(1)};
        }
        return new String[]{monitoringTypeName};
    }

    public static void main(String[] args) {
        Pattern p = Pattern.compile("([^()]+)(\\(([^()]+)\\))?");
        Matcher m = p.matcher("nnn(yes)");
        System.err.println(m.groupCount());
        while (m.find()) {
            System.err.println(m.group());
        }
    }
}
